package kr.hyunist.musicplayexer;

import kr.hyunist.musicplayexer.Application.MediaApplication;
import kr.hyunist.musicplayexer.Util.Util;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.graphics.Bitmap;
import android.media.AudioManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.RemoteException;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;

public class PlayDetail extends Activity {
	Intent in = null;
	MediaApplication app;	//어플리케이션 객체
	private final int NO_REPEAT = 0; // 반복없음
	private final int REPEAT_ONE = 1; // 한곡반복
	private final int REPEAT_ALL = 2; // 전체반복
	private int CURRENT_REPEAT_MODE = -1; // 현재 반복 모드

	private final String DETAIL_PREFS = "MusicPlayerSetting";
	private final String SHUFFLE_STATE = "shuffle_state";
	private final String REPEAT_STATE = "repeat_state";

	private Button mRepeat; // 반복버튼
	private Button mShuffle; // 셔플버튼
	private Button btnPlayOrPause;	//재생, 일시중지

	SeekBar progressSeek; // 진행시크바
	Handler mProgressHandler;	//진행 시크바 핸들러
	Runnable runnable;	//진행 시크바 스레드
	TextView dNowPlayTime; // 재생시간
	
	TextView dTitle;
	TextView dArtist;
	TextView dPlayTime;
	ImageView dImage;
	Bitmap detailAlbumArt;
	
	boolean SHUFFLESTATE;
	boolean wasPlaying;
	
	@Override
	protected void onStart() {
		super.onStart();
		getPreferences();
		Log.d(ListMainActivity.TAG, "Detail 액티비티 : onstart");
		Log.d(ListMainActivity.TAG, "Detail 액티비티 shuffleState상태 : " + SHUFFLESTATE);
		Log.d(ListMainActivity.TAG, "Detail 액티비티 repeatState상태 : " + CURRENT_REPEAT_MODE);
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.playdetail);

		// 어플리케이션 객체 생성
		app = (MediaApplication) getApplication();
		Log.d(ListMainActivity.TAG, "상세 페이지의 app 주소값 : " + app);
		Log.d(ListMainActivity.TAG, "전역 서비스의 주소값은? : " + app.mService);

		// 현재 재생 되는 음악에 대한 정보를 가져옴
		dTitle = (TextView) findViewById(R.id.txtTitle);
		dArtist = (TextView) findViewById(R.id.txtArtist);
		dPlayTime = (TextView) findViewById(R.id.nowplayTime);
		dNowPlayTime = (TextView) findViewById(R.id.nowTime);
		dImage = (ImageView) findViewById(R.id.songimage);
		
		//볼륨조절
		seekVolume();
		
		if (app.getCurrentPosition() >= 0) {
			if (app.mPlayer != null && app.mPlayer.isPlaying()) {
				CurrentSongInfo();
				seekProgress();
			} else if (app.mPlayer != null && !app.mPlayer.isPlaying()) {

			}
		}
		
		/*CurrentSongInfo();
		seekVolume();
		seekProgress();*/
		
		// 반복 여부 확인
		mRepeat = (Button) findViewById(R.id.btnRepeat);

		// 셔플 여부 확인
		mShuffle = (Button) findViewById(R.id.btnShuffle);

		// 재생&일시중지, 이전, 다음버튼 찾아놓고
		btnPlayOrPause = (Button) findViewById(R.id.btnPlayOrPause);
		
		// 진행 시크바
		progressSeek = (SeekBar) findViewById(R.id.songprogress);
		progressSeek.setOnSeekBarChangeListener(mOnProgressSeek);
	}

	private void seekProgress() {
		// 진행 시크바
		mProgressHandler = new Handler();
		runnable = new Runnable() {

			@Override
			public void run() {
				mProgressHandler.postDelayed(runnable, 200);
				try {
					if (app.mPlayer.isPlaying()) {
						progressSeek.setMax(app.mPlayer.getDuration());
						progressSeek.setProgress(app.mPlayer.getCurrentPosition());
					}

					dNowPlayTime.setText(Util.milliSecToTime(String.valueOf(app.mPlayer.getCurrentPosition())));
				} catch (Exception e) {
					
				}

			}
		};

		mProgressHandler.postDelayed(runnable, 200);
	}

	// 진행 시크바 이벤트 처리
	SeekBar.OnSeekBarChangeListener mOnProgressSeek = new OnSeekBarChangeListener() {

		@Override
		public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
			if (fromUser) {
				app.mPlayer.seekTo(progress);
			}
		}
		
		@Override
		public void onStopTrackingTouch(SeekBar seekBar) {
		}

		@Override
		public void onStartTrackingTouch(SeekBar seekBar) {
		}

	};
	
	private void seekVolume() {
		// 볼륨 시크바
		SeekBar seekVolumn = (SeekBar) findViewById(R.id.volumeseek);
		final AudioManager audioManager = (AudioManager) getSystemService(AUDIO_SERVICE);
		int nMax = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
		int nCurrentVolumn = audioManager
				.getStreamVolume(AudioManager.STREAM_MUSIC);
		seekVolumn.setMax(nMax);
		seekVolumn.setProgress(nCurrentVolumn);
		seekVolumn.setOnSeekBarChangeListener(new OnSeekBarChangeListener() {

			@Override
			public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
				audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, progress, 0);
			}

			@Override
			public void onStartTrackingTouch(SeekBar seekBar) {
			}

			@Override
			public void onStopTrackingTouch(SeekBar seekBar) {
			}

		});	
	}

	//버튼 이벤트 처리
	public void onMediaControl(View v) throws Exception {
		switch (v.getId()) {
		case R.id.btnPlayOrPause:
			if (app.mPlayer != null) {
				if (app.mPlayer.isPlaying() == false) {
					app.mPlayer.start();
					btnPlayOrPause.setBackgroundResource(R.drawable.pausebtn_selector);
				} else {
					app.mPlayer.pause();
					btnPlayOrPause.setBackgroundResource(R.drawable.playbtn_selector);
				}
			} else {
				app.mService.onListItemSelectplayBackMusic(app.getCurrentPosition());
				btnPlayOrPause.setBackgroundResource(R.drawable.pausebtn_selector);
			}

			break;
			
		case R.id.btnBack:	
		case R.id.btnNext:
			wasPlaying = app.mPlayer.isPlaying();
			
			if(v.getId() == R.id.btnBack){
				app.mService.prev();
				btnPlayOrPause.setBackgroundResource(R.drawable.pausebtn_selector);
			} else {		        
				app.mService.next();
				btnPlayOrPause.setBackgroundResource(R.drawable.pausebtn_selector);
			}
			
			CurrentSongInfo();
			app.mPlayer.reset();
			app.mService.onListItemSelectplayBackMusic(app.getCurrentPosition());
			
			break;
			
		case R.id.btnRepeat:
			CURRENT_REPEAT_MODE++;
			if (CURRENT_REPEAT_MODE > REPEAT_ALL) {
				CURRENT_REPEAT_MODE = 0;
			}

			switch (CURRENT_REPEAT_MODE) {
			case NO_REPEAT:	//0
				mRepeat.setBackgroundResource(R.drawable.repeatno_selector);
				Log.d(ListMainActivity.TAG, "반복없음 상태의 반복 재생 값 : " + CURRENT_REPEAT_MODE);
				Log.d(ListMainActivity.TAG, "반복없음 상태의 반복 재생 값 : " + app.mService.getRepeatMode());
				break;
			case REPEAT_ONE:	//1
				mRepeat.setBackgroundResource(R.drawable.repeatone_selector);
				//app.mService.setRepeatMode(REPEAT_ONE);
				//app.mService.getRepeatMode();
				Log.d(ListMainActivity.TAG, "한곡반복 상태의 반복 재생 값 : " + CURRENT_REPEAT_MODE);
				Log.d(ListMainActivity.TAG, "한곡반복 상태의 반복 재생 값 : " + app.mService.getRepeatMode());
				break;
			case REPEAT_ALL:	//2
				mRepeat.setBackgroundResource(R.drawable.repeatall_selector);
				//app.mService.setRepeatMode(REPEAT_ALL);
				//app.mService.getRepeatMode();
				Log.d(ListMainActivity.TAG, "전체반복 상태의 반복 재생 값 : " + CURRENT_REPEAT_MODE);
				Log.d(ListMainActivity.TAG, "전체반복 상태의 반복 재생 값 : " + app.mService.getRepeatMode());
				break;
			default:
				break;
			}

			break;
			
		case R.id.btnShuffle:
			app.isShuffle = !app.isShuffle;
			
			Log.d(ListMainActivity.TAG, "app.isShuffle()의 상태 : " + app.isShuffle);
			
			mShuffle.setBackgroundResource(app.isShuffle ? R.drawable.shuffleon_selector : R.drawable.shuffleoff_selector);
			break;
		}
	}
	
	//현재 재생 되는 음원정보 출력
	public void CurrentSongInfo() {
		//음원 제목
		dTitle.setText(app.getArList().get(app.getCurrentPosition()).getMusicTitle());

		//음악가 정보
		dArtist.setText(app.getArList().get(app.getCurrentPosition()).getArtist());

		//음원 이미지 정보
		detailAlbumArt = Util.getArtworkQuick(PlayDetail.this, Integer.parseInt((app.getArList().get(app.getCurrentPosition()).getAlbumID())), 500, 500);
		if (detailAlbumArt == null){
			dImage.setImageResource(R.drawable.noimagebig);
		} else {
			dImage.setImageBitmap(detailAlbumArt);
		}
		
		//재생시간 정보
		dPlayTime.setText(app.getArList().get(app.getCurrentPosition()).getPlayTime());		
	}

	@Override
	protected void onPause() {
		super.onPause();
		savePreferences();	//상태저장
		Log.d(ListMainActivity.TAG, "savePreferences() : 실행됨");
	}

	// 저장 상태 불러오기
	private void getPreferences() {
		SharedPreferences pref = getSharedPreferences(DETAIL_PREFS, 0);
	
		SHUFFLESTATE = pref.getBoolean(SHUFFLE_STATE, false);
		CURRENT_REPEAT_MODE = pref.getInt(REPEAT_STATE, NO_REPEAT);
		
		Log.d(ListMainActivity.TAG, "int shuffleState값 : " + SHUFFLESTATE);
		Log.d(ListMainActivity.TAG, "int repeatState값 : " + CURRENT_REPEAT_MODE);
		
		//셔플상태 불러와서 설정
		if(SHUFFLESTATE){
			mShuffle.setBackgroundResource(R.drawable.shuffleon_selector);	
		} else {
			mShuffle.setBackgroundResource(R.drawable.shuffleoff_selector);
		}
		
		//반복상태 불러와서 설정
		switch(CURRENT_REPEAT_MODE){
		case 0:
			try {
				app.mService.setRepeatMode(NO_REPEAT);
				mRepeat.setBackgroundResource(R.drawable.repeatno_selector);
			} catch (RemoteException e) {
				
			}
			
			break;
			
		case 1:
			try {
				app.mService.setRepeatMode(REPEAT_ONE);
				mRepeat.setBackgroundResource(R.drawable.repeatone_selector);
			} catch (RemoteException e) {
				
			}
			
			break;
			
		case 2:
			try {
				app.mService.setRepeatMode(REPEAT_ALL);
				mRepeat.setBackgroundResource(R.drawable.repeatall_selector);
			} catch (RemoteException e) {
				
			}
			
			break;
		}
		

	}

	// 설정값 저장하기
	private void savePreferences() {
		SharedPreferences pref = getSharedPreferences(DETAIL_PREFS, 0);
		SharedPreferences.Editor editor = pref.edit();
		editor.putBoolean(SHUFFLE_STATE, app.isShuffle);
		editor.putInt(REPEAT_STATE, CURRENT_REPEAT_MODE);
		editor.commit();
	}
	
	@Override
	protected void onDestroy() {
		super.onDestroy();
		Log.d(ListMainActivity.TAG, "Detail의 onDestroy");
	}
	
	@Override
	public void onBackPressed() {
		super.onBackPressed();
		overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_down);
	}
	
}
